package com.example.demo.service.iml;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mapper.DeviceMapper;
import com.example.demo.mapper.UserDeviceBindingMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.Device;
import com.example.demo.pojo.User;
import com.example.demo.pojo.UserDeviceBinding;
import com.example.demo.service.UserDeviceBindingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

@Service
public class UserDeviceBindingServiceImpl implements UserDeviceBindingService {

    @Autowired
    private UserDeviceBindingMapper bindingMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public String saveBinding(String imei, String openId) {
        // 查找或创建用户
        User user = userMapper.findByOpenId(openId);
        if (user == null) {
            user = new User();
            user.setOpenId(openId);
            userMapper.insert(user);
        }

        // 查找或创建设备
        Device device = deviceMapper.findByImei(imei);
        if (device == null) {
            device = new Device();
            device.setImei(imei);
            deviceMapper.insert(device);
        }

        // 创建绑定关系
        UserDeviceBinding binding = new UserDeviceBinding();
        binding.setOpenId(openId);
        binding.setImei(imei);
        binding.setBindingTime(LocalDateTime.now());

        int result = bindingMapper.insert(binding);
        if (result > 0) {
            return "绑定成功";
        } else {
            return "绑定失败";
        }
    }

    @Override
    public String getOpenidByImei(String imei) {
        // 使用MyBatis-Plus的Lambda查询
        UserDeviceBinding binding = bindingMapper.selectOne(
                new QueryWrapper<UserDeviceBinding>()
                        .eq("imei", imei)
                        .orderByDesc("binding_time")
                        .last("LIMIT 1")
        );

        // 如果找到绑定关系，返回open_id，否则返回null
        return binding != null ? binding.getOpenId() : null;
    }

    @Override
    public String cancelBinding(String imei, String openId) {
        QueryWrapper<UserDeviceBinding> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("imei", imei).eq("open_id", openId);

        int result = bindingMapper.delete(queryWrapper);

        if (result > 0) {
            return "解绑成功";
        } else {
            return "解绑失败，未找到对应的绑定关系";
        }
    }
}